<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 页面主体区 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入用户名" v-model="paramsInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="12">
          <p style="color:white;">'</p>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="saveChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditUser(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id,scope.row.username)"
            ></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页部分 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paramsInfo.pagenum"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="paramsInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户窗口 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addCloseHandle">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户窗口 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editCloseHandle">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色窗口 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleHandle">
      <div>
        <p>当前用户名：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      var regEmail = /^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
      if (regEmail.test(value) || "" == value) {
        return callback();
      } else {
        callback(new Error("电子邮箱格式不正确！"));
      }
    };

    var checkMobile = (rule, value, callback) => {
      var regMoblie = /^1\d{10}$/;
      if (regMoblie.test(value) || "" == value) {
        return callback();
      } else {
        callback(new Error("手机号码格式不正确！"));
      }
    };

    return {
      userList: [],
      roleList: [],
      userInfo: "",
      selectedRoleId: "",
      userId: "",
      paramsInfo: {
        query: "",
        pagenum: 1,
        pagesize: 3
      },
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      setRoleDialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      editForm: {},
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: false, message: "请输入电子邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: false, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      editFormRules: {
        email: [
          { required: false, message: "请输入电子邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: false, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.paramsInfo
      });
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg + "，获取管理员列表失败");
      } else {
        this.userList = res.data.users;
        this.total = res.data.total;
      }
    },
    handleSizeChange(newSize) {
      this.paramsInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.paramsInfo.pagenum = newPage;
      this.getUserList();
    },
    async saveChange(changeInfo) {
      const { data: res } = await this.$http.put(
        `users/${changeInfo.id}/state/${changeInfo.mg_state}`
      );
      // console.log(res);
      if (res.meta.status !== 200) {
        changeInfo.mg_state = !changeInfo.mg_state;
        return this.$message.error(res.meta.msg + "，状态修改失败");
      } else if (res.meta.status == 200) {
        // this.$message.success(res.meta.msg + "，状态修改成功");
        this.$message.success("状态修改成功");
      } else {
        return this.$message.error(res.meta.msg + "，请联系管理员");
      }
    },
    addCloseHandle() {
      this.$refs.addFormRef.resetFields();
    },
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("表单内容格式不正确！");
        } else {
          const { data: res } = await this.$http.post("users", this.addForm);
          // console.log(res);
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg);
          } else {
            this.$message.success(res.meta.msg);
            this.addDialogVisible = false;
            this.getUserList();
          }
        }
      });
    },
    async showEditUser(id) {
      const { data: res } = await this.$http.get("users/" + id);
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        this.editForm = res.data;
        this.editDialogVisible = true;
      }
    },
    editCloseHandle() {
      this.$refs.editFormRef.resetFields();
    },
    editUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("表单内容格式不正确！");
        } else {
          const { data: res } = await this.$http.put(
            "users/" + this.editForm.id,
            { email: this.editForm.email, mobile: this.editForm.mobile }
          );
          // console.log(this.editForm);
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg);
          } else {
            this.$message.success(res.meta.msg);
            this.editDialogVisible = false;
            this.getUserList();
          }
        }
      });
    },
    async deleteUser(id, username) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      } else {
        const { data: res } = await this.$http.delete("users/" + id);
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg + "删除失败");
        } else {
          this.$message.success("用户" + username + "已被删除成功!");
          this.getUserList();
        }
      }
    },
    async showSetRoleDialog(user) {
      this.userInfo = user;
      this.userId = user.id;
      // console.log(this.userInfo);
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        this.roleList = res.data;
        this.setRoleDialogVisible = true;
      }
    },
    async editUserRole() {
      if (!this.selectedRoleId) {
        return this.$message.warning("请选择需要分配的角色");
      } else {
        const { data: res } = await this.$http.put(
          `users/${this.userId}/role`,
          {
            rid: this.selectedRoleId
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        } else {
          this.$message.success(res.meta.msg);
          this.setRoleDialogVisible = false;
          this.getUserList();
        }
      }
    },
    setRoleHandle() {
      this.userInfo = "";
      this.selectedRoleId = "";
    }
  }
};
</script>

<style lang='less' scoped>
</style>